﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using TMDT_Nhom1A.DTO;
using TMDT_Nhom1A.utils;
using System.Collections.Generic;
using System.Collections;

namespace TMDT_Nhom1A.DAO
{
    public class CouponWebservice_DAO
    {
        private static QL_DoanhNghiepDataContext qldoanhnghiep = new QL_DoanhNghiepDataContext();

        #region Authenticate
        public static string Authenticate(string username, string password)
        {
            try
            {
                var result = from user in qldoanhnghiep.USERs
                             join reg in qldoanhnghiep.REGISTRY_WEBSERVICEs on user.UserID equals reg.UserId
                             where user.Username.Equals(username.Trim()) && user.Password.Equals(MyMembershipProvider.ToHashString(password.Trim() + username.Trim())) && reg.Activate == true && reg.Status == 1
                             select user;

                if (result.Count() == 1)
                {
                    USER user = result.First();
                    if (user.Activate == true)
                    {

                        if (user.Status != 1)
                        {
                            return "2";
                        }
                        else
                        {
                           
                                string sid = username + password + DateTime.Now.ToString("yyyyMMddhhmmss");
                                sid = GenerateUtil.CreateSessionID(sid);
                                

                                //kiem tra sid nay da luu trong bang log_transition chua
                                var isExistSid = qldoanhnghiep.LOG_TRANSITIONs.Where(c => c.Sid == (sid.Trim()));
                                if (isExistSid.Count() >= 1)
                                {
                                    return sid;
                                }
                                else
                                {
                                    //luu xuong database
                                    LOG_TRANSITION log_transition = new LOG_TRANSITION();
                                    log_transition.Sid = sid.Trim();
                                    log_transition.UserID = user.UserID;
                                    

                                    qldoanhnghiep.LOG_TRANSITIONs.InsertOnSubmit(log_transition);
                                    qldoanhnghiep.SubmitChanges();
                                }

                                return sid;
                            
                        }
                    }
                    else
                    {
                        return "1";
                    }


                }
                else
                {
                    return "4";
                }
            }
            catch (Exception ex)
            {
                return "5";
            }
        }
        #endregion

        #region CheckSid
        //kiem tra sid co ton tai trong database chua?
        public static bool CheckSid(string sid)
        {
            try
            {
                int isExistSid = qldoanhnghiep.LOG_TRANSITIONs.Where(c => c.Sid == sid.Trim()).Count();
                if (isExistSid >= 1)
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }
        #endregion

        #region FindAllCoupons
        public static Coupon[] FindAllCoupons(string path)
        {
            List<Coupon> coupons = new List<Coupon>();

            var result = from c in qldoanhnghiep.COUPONs
                         join e in qldoanhnghiep.ELECTRIC_DEVICEs on c.ElectricDevice_ID equals e.ElectricDevice_ID
                         join b in qldoanhnghiep.BRANDs on e.Brand_ID equals b.Brand_ID
                         join cur in qldoanhnghiep.CURRENCies on e.Currency_ID equals cur.Currency_ID
                         where c.Status == 1
                         select new
                         {
                             c.Coupon_ID,
                             e.ElectricDevice_ID,
                             e.ElectricDevice_Name,
                             b.Brand_ID,
                             b.Brand_Name,
                             c.NonDiscountPrice,
                             c.DiscountPrice,
                             c.QuantityForDiscountPrice,
                             cur.Currency_ID,
                             c.TimeToStartSelling,
                             c.TimeToEndSelling,
                             c.TimeToStartUsing,
                             c.TimeToEndUsing,
                             c.Description,
                             c.UsingCondition,
                             e.ImagePath,
                             e.NumberOfBuyers
                         };

            //copy data to list<coupon>
            foreach (var item in result)
            {
                Coupon coupon = new Coupon();
                coupon = CouponWebservice_DAO.FindCouponInfo(item.Coupon_ID, path);
                coupons.Add(coupon);
            }

            return coupons.ToArray();
        }
        #endregion

        #region CalculateOrderQuantity
        //tinh so luong dat 1 coupon
        private static int CalculateOrderQuantity(string couponID)
        {
            var OrderQuantity = from order in qldoanhnghiep.ORDER_COUPON_DETAILs
                                where order.Coupon_ID.Equals(couponID)
                                select order;

            int sum = 0;
            foreach (var orderQuantityItem in OrderQuantity)
            {
                sum += (int)orderQuantityItem.Quantity;
            }
            return sum;
        }
        #endregion

        #region FindCoupons
        public static Coupon[] FindCoupons(string productName, DateTime startDate, DateTime endDate, int minPrice, int maxPrice, short flag, string path)
        {
            var result = qldoanhnghiep.spFindCouponWithKeyWord(productName, startDate, endDate, minPrice, maxPrice, flag);

            List<Coupon> coupons = new List<Coupon>();
            foreach (var item in result)
            {
                Coupon coupon = new Coupon();
                coupon = CouponWebservice_DAO.FindCouponInfo(item.Coupon_ID, path);
                coupons.Add(coupon);
            }

            return coupons.ToArray();
        }
        #endregion


        public static Coupon[] FindCoupons(string[] parameterNames, string[] parameterValues)
        {
            return null;
        }

        #region FindCouponInfo
        public static Coupon FindCouponInfo(string couponId, string path)
        {
            var result = from c in qldoanhnghiep.COUPONs
                         join e in qldoanhnghiep.ELECTRIC_DEVICEs on c.ElectricDevice_ID equals e.ElectricDevice_ID
                         join b in qldoanhnghiep.BRANDs on e.Brand_ID equals b.Brand_ID
                         join cur in qldoanhnghiep.CURRENCies on e.Currency_ID equals cur.Currency_ID
                         where c.Status == 1 && c.Coupon_ID == couponId
                         select new
                         {
                             c.Coupon_ID,
                             e.ElectricDevice_ID,
                             e.ElectricDevice_Name,
                             b.Brand_ID,
                             b.Brand_Name,
                             c.NonDiscountPrice,
                             c.DiscountPrice,
                             c.QuantityForDiscountPrice,
                             cur.Currency_ID,
                             c.TimeToStartSelling,
                             c.TimeToEndSelling,
                             c.TimeToStartUsing,
                             c.TimeToEndUsing,
                             c.Description,
                             c.UsingCondition,
                             e.ImagePath,
                             e.NumberOfBuyers
                         };

            Coupon coupon = new Coupon();
            //copy data to list<coupon>
            foreach (var item in result)
            {

                coupon.MaCoupon = item.Coupon_ID;
                coupon.MaMatHang = item.ElectricDevice_ID;
                coupon.TenMatHang = item.ElectricDevice_Name;
                coupon.MaNhaCungCap = item.Brand_ID.ToString();
                coupon.TenNhaCungCap = item.Brand_Name;
                coupon.GiaHangKhiChuaGiam = item.NonDiscountPrice;
                coupon.GiaHangSauKhiGiam = item.DiscountPrice;
                coupon.DonViTien = item.Currency_ID;
                coupon.SoLuongThoaCoupon = item.QuantityForDiscountPrice.Value;
                //if (item.NumberOfBuyers != null)
                //    coupon.SoLuongMuaLonNhat = (int)item.NumberOfBuyers;
                coupon.SoLuongMuaLonNhat = item.QuantityForDiscountPrice.Value;
                coupon.NgayBatDau = (DateTime)item.TimeToStartSelling;
                coupon.NgayKetThuc = item.TimeToEndSelling.Value;
                coupon.NgayCouponBatDauDuocSuDung = item.TimeToStartUsing.Value;
                coupon.NgayCouponHetHan = item.TimeToEndUsing.Value;
                coupon.ThongTinMoTa = item.Description;
                coupon.DieuKienSuDung = item.UsingCondition;


                coupon.LinkHinhAnh[0] = path + item.ImagePath;
                coupon.SoLuongDaDat = CouponWebservice_DAO.CalculateOrderQuantity(item.Coupon_ID);

                return coupon;
            }

            return null;
        }
        #endregion

        #region RegisterCoupon
        public static bool RegisterCoupon(string sid, string couponId)
        {
            try
            {
                //tim userID
                int userID = (from log_trans in qldoanhnghiep.LOG_TRANSITIONs
                              where log_trans.Sid == sid
                              select log_trans.UserID).Single();

                //Chi duoc dang ki coupon trong khoang thoi gian ban' coupon
                COUPON coupon = qldoanhnghiep.COUPONs.Single(cp => cp.Coupon_ID == couponId);
                if (DateTime.Now >= coupon.TimeToStartSelling && DateTime.Now <= coupon.TimeToEndSelling)
                {
                    //kiem tra xem user nay dang ki couponId nay chua
                    var checkResult = from resgisterCoupon in qldoanhnghiep.REGISTRY_COUPONs
                                      where resgisterCoupon.Coupon_ID == couponId && resgisterCoupon.UserID == userID
                                      select resgisterCoupon;
                    if (checkResult.Count() >= 1)
                    {
                        return false;
                    }
                    //insert vao table registry_coupon
                    REGISTRY_COUPON registryCoupon = new REGISTRY_COUPON();
                    registryCoupon.Coupon_ID = couponId;
                    registryCoupon.UserID = userID;
                    registryCoupon.RegisterDate = DateTime.Now;

                    qldoanhnghiep.REGISTRY_COUPONs.InsertOnSubmit(registryCoupon);

                    qldoanhnghiep.SubmitChanges();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }


        }
        #endregion

        #region OrderCoupon
        public static string OrderCoupon(string sid, string couponId, int count)
        {
            try
            {
                // Chi duoc dat mua trong khoang thoi gian su dung coupon
                COUPON coupon = (from c in qldoanhnghiep.COUPONs
                                 where c.Coupon_ID == couponId
                                 select c).Single();

                if (DateTime.Now >= coupon.TimeToStartUsing && DateTime.Now <= coupon.TimeToEndUsing)
                {

                    //tim userID
                    int userID = (from log_trans in qldoanhnghiep.LOG_TRANSITIONs
                                  where log_trans.Sid == sid
                                  select log_trans.UserID).Single();

                    //kiem tra la username nay co registry coupon_id nay chua
                    var result = from registryCoupon in qldoanhnghiep.REGISTRY_COUPONs
                                 where registryCoupon.UserID == userID && registryCoupon.Coupon_ID == couponId
                                 select registryCoupon;

                    //neu ton tai
                    if (result.Count() == 1)
                    {
                        //kiem tra so luong (count) > 0
                        if (count > 0)
                        {
                            //phat sinh ra validationCode moi
                            string validationCode = "";
                            int maxRow = CouponUtil.GetMaxRowFromOrderCouponTable(qldoanhnghiep);
                            validationCode = GenerateUtil.GenerateValidationCode(maxRow);

                            //luu validationCode vao bang log_transition

                            // luu vao bang log_order_coupon
                            LOG_ORDER_COUPON logOrderCoupon = new LOG_ORDER_COUPON();
                            logOrderCoupon.Sid = sid;
                            logOrderCoupon.ValidationCode = validationCode;
                            logOrderCoupon.CouponID = couponId;
                            logOrderCoupon.Count = count;

                            qldoanhnghiep.LOG_ORDER_COUPONs.InsertOnSubmit(logOrderCoupon);
                            qldoanhnghiep.SubmitChanges();

                            return validationCode;
                        }
                        else
                        {
                            return ErrorCode.InvalidQuantityERR;
                        }
                    }
                    else
                    {
                        return ErrorCode.RegistryCouponERR;
                    }


                }
                else
                {
                    return ErrorCode.TimeOutOrderCouponERR;
                }
                
              
            }
            catch
            {
                return ErrorCode.OrderCouponERR;
            }
        }
        #endregion

        #region ValidateOrder
        public static bool ValidateOrder(string sid, string validationCode)
        {
            try
            {
                //tim userID
                int userID = (from log_trans in qldoanhnghiep.LOG_TRANSITIONs
                              where log_trans.Sid == sid.Trim()
                              select log_trans.UserID).Single();

                //kiem tra trong ban log_order_coupon cot validateCode co bi NULL ko ung voi sid
                var LogOrderCouponResult = from logOrderCoupon in qldoanhnghiep.LOG_ORDER_COUPONs
                                           where logOrderCoupon.Sid == sid && logOrderCoupon.ValidationCode == validationCode
                                           select logOrderCoupon;

                if (LogOrderCouponResult.Count() == 1)
                {
                    //kiem tra validationCode nay ton tai ben bang orderCoupon hay chua
                    var orderCouponResult = from orderCoupon in qldoanhnghiep.ORDER_COUPONs
                                            where orderCoupon.OrderCouponID == validationCode
                                            select orderCoupon;
                    if (orderCouponResult.Count() >= 1)
                    {
                        return false;                       
                    }
                    else
                    {
                        //neu chua co luu xuong database
                        //doc du lieu tu bang log_order_coupon
                        LOG_ORDER_COUPON logOrderCoupon = LogOrderCouponResult.Single();

                        ORDER_COUPON newOrderCoupon = new ORDER_COUPON();
                        newOrderCoupon.OrderCouponID = logOrderCoupon.ValidationCode;
                        newOrderCoupon.OrderedDate = DateTime.Now;
                        newOrderCoupon.PaymentSatus = 0;
                        newOrderCoupon.status = 0;
                        newOrderCoupon.TransportStatus = 0;
                        newOrderCoupon.UserID = userID;
                        newOrderCoupon.TransportType = null;

                        ORDER_COUPON_DETAIL newOrderCouponDetail = new ORDER_COUPON_DETAIL();
                        newOrderCouponDetail.Coupon_ID = logOrderCoupon.CouponID;
                        newOrderCouponDetail.OrderCouponID = logOrderCoupon.ValidationCode;
                        newOrderCouponDetail.Quantity = logOrderCoupon.Count;
                        newOrderCoupon.ORDER_COUPON_DETAILs.Add(newOrderCouponDetail);
                        qldoanhnghiep.ORDER_COUPONs.InsertOnSubmit(newOrderCoupon);
                        qldoanhnghiep.SubmitChanges();
                    }
                }
                else
                {
                    return false;
                }
                
                //// xoa tat ca du lieu ben bang Log_order_coupon 
                foreach (var logOrderCouponItem in LogOrderCouponResult)
                {

                    qldoanhnghiep.LOG_ORDER_COUPONs.DeleteOnSubmit(logOrderCouponItem);
                    qldoanhnghiep.SubmitChanges();
                }

                return true;

            }
            catch
            {
                return false;
            }
        }
        #endregion
        
        #region CancelOrder
        public static bool CancelOrder(string validationCode)
        {
            try
            {
                var result = qldoanhnghiep.ORDER_COUPONs.Where(o => o.OrderCouponID == validationCode);

                if (result.Count() == 1)
                {
                    ORDER_COUPON orderCoupon = result.First();
                    var orderCouponDetailList = qldoanhnghiep.ORDER_COUPON_DETAILs.Where(x => x.OrderCouponID == validationCode);

                    qldoanhnghiep.ORDER_COUPON_DETAILs.DeleteAllOnSubmit(orderCouponDetailList);
                    qldoanhnghiep.ORDER_COUPONs.DeleteOnSubmit(orderCoupon);
                    qldoanhnghiep.SubmitChanges();

                    return true;

                }
                else
                    return false;
            }
            catch
            {
                return false;
            }

        }
        #endregion

        #region GetTranports
        public static TMDT_Nhom1A.TransportWS.TransportCompany[] GetTranports()
        {
            try
            {
                List<TMDT_Nhom1A.TransportWS.TransportCompany> transCompanyList = new List<TMDT_Nhom1A.TransportWS.TransportCompany>();
                // lay ra tat ca transport_webservice
                var transportCompanyResult = from transCompany in qldoanhnghiep.TRANSPORT_WEBSERVICEs
                                             select transCompany;

                //load WS cua tung van chuyen do
                foreach (var transportCompanyItem in transportCompanyResult)
                {
                    //ket noi toi WS
                    TransportWS.FedexWebService1 transportWS = new TMDT_Nhom1A.TransportWS.FedexWebService1();
                    string transportUrl = CouponUtil.GetUrlTransportWebservice(qldoanhnghiep, transportCompanyItem.TRANSPORT_WS_ID.ToString());
                    transportWS.Url = transportUrl;

                    //goi ham getTransport cua van chuyen
                    TMDT_Nhom1A.TransportWS.TransportCompany transCompany = transportWS.GetTranports();
                    transCompany.MaCongTyVanChuyen = transportCompanyItem.TRANSPORT_WS_ID.ToString();
                    transCompanyList.Add(transCompany);

                }

                return transCompanyList.ToArray();

               
            }
            catch
            {
                return null;
            }
            
        }
        #endregion



        public static bool CallWebserviceFromMuaChung(string validationCode)
        {
            bool kq = false;
            try
            {
                MuaChungWS.MuaChungWS muaChungWS = new TMDT_Nhom1A.MuaChungWS.MuaChungWS();

                //tim userID nao dat validationCode nay
                int userID = (from orderCoupon in qldoanhnghiep.ORDER_COUPONs
                             where orderCoupon.OrderCouponID == validationCode
                             select orderCoupon.UserID).Single();

                //lay webservice van chuyen dang xai
                string MuaChungWS_Url = CouponUtil.GetUrlMuaChungWebservice(qldoanhnghiep,userID);
                muaChungWS.Url = MuaChungWS_Url;

                //chung thuc Mua chung WS (lay account tu AccountMuaChungWebservice Table) ung voi userID
                string userName = "";
                string passWord = "";
                var accountMuaChungResult = from acc in qldoanhnghiep.AccountMuaChungWebservices
                                            where acc.User_ID == userID
                                            select acc;
                if (accountMuaChungResult.Count() == 1)
                {
                    AccountMuaChungWebservice accMucChung = accountMuaChungResult.Single();
                    userName =  accMucChung.Username;
                    passWord = accMucChung.Password;
                }

                string sid = muaChungWS.Authenticate(userName, passWord);

                if(sid != "" && sid != null)
                {
                    //lay tat cac couponId duoc dat voi validationCode
                    var orderCouponDetailResult = from orderCouponDetail in qldoanhnghiep.ORDER_COUPON_DETAILs
                                                  where orderCouponDetail.OrderCouponID == validationCode
                                                  select orderCouponDetail;

                    if (orderCouponDetailResult.Count() >= 1)
                    {
                        foreach (var item in orderCouponDetailResult)
                        {
                            //lay ra couponID
                            string couponID = item.Coupon_ID;
                            Coupon couponInfo  =  CouponWebservice_DAO.FindCouponInfo(couponID,"");

                            //kiem tra la xem co du so luong de mua coupon dat gia tot nhat ko?
                            if (couponInfo.SoLuongDaDat < couponInfo.SoLuongThoaCoupon)
                            {
                                kq = muaChungWS.ConfirmCoupon(sid, couponInfo.MaCoupon, float.Parse(couponInfo.GiaHangKhiChuaGiam), couponInfo.DonViTien);
                            }
                            else
                            {
                                kq = muaChungWS.ConfirmCoupon(sid, couponInfo.MaCoupon, float.Parse(couponInfo.GiaHangSauKhiGiam), couponInfo.DonViTien);
                            }
                            
                        }
                    }
                }

                return kq;
            }
            catch
            {
                return false;
            }
        }



        public static string ConfirmOrder(string transCompanyId, string transTypeId, string validationCode, ContactInfo contact)
        {
            string url = "";
            try
            {
               

                //kiem tra co ton tai transportCompanyID nay ko
                var checkTransportCompanyID = from transCompany in qldoanhnghiep.TRANSPORT_WEBSERVICEs
                                              where transCompany.TRANSPORT_WS_ID == int.Parse(transCompanyId)
                                              select transCompany;
                if(checkTransportCompanyID.Count() == 1)
                {
                    //goi WS van chuyen
                    TransportWS.FedexWebService1 transportWS = new TMDT_Nhom1A.TransportWS.FedexWebService1();

                    //lay thong tin url Webservice van chuyen dang xai
                    string transportUrl = CouponUtil.GetUrlTransportWebservice(qldoanhnghiep, transCompanyId);
                    transportWS.Url = transportUrl;

                    string userName = "";
                    string passWord = "";
                    //gọi hàm authenticate
                    var accountTransportWS = from acc in qldoanhnghiep.AccountTransportWebservices
                                             where acc.TransportWS_ID == int.Parse(transCompanyId)
                                             select acc;
                    if(accountTransportWS.Count() == 1)
                    foreach (var accountItem in accountTransportWS)
                    {
                        userName = accountItem.Username;
                        passWord = accountItem.Password;
                    }

                    //goi ham authenticate
                    string sid = transportWS.Authenticate(userName,passWord);


                    if (sid != "" && sid != null)
                    {
                         //lay tat cac couponId duoc dat voi validationCode
                        var orderCouponDetailResult = from orderCouponDetail in qldoanhnghiep.ORDER_COUPON_DETAILs
                                                      where orderCouponDetail.OrderCouponID == validationCode
                                                      select orderCouponDetail;




                        if (orderCouponDetailResult.Count() >= 1)
                        {
                            

                            foreach (var item in orderCouponDetailResult)
                            {
                                //lay ra couponID  
                                //tao ra dia chi
                                //string customerAddress = contact.Email + "||" + contact.SoDienThoai + "||" + contact.DiaChi;
                                string customerAddress = contact.DiaChi;
                                url = transportWS.TransportGoods(sid, item.Coupon_ID, int.Parse(item.Quantity.ToString()), DateTime.Now, customerAddress, int.Parse(transTypeId), "Q4, Nha Trang");

                            }
                        }
                        else
                        {
                            return ErrorCode.ConfirmOrderNotExistValidationCodeERR;
                        }
                       
                    }
                }
                                                        
                return url;
            
            }
            catch
            {
                return ErrorCode.ConfirmOrderERR;
            }
        }


        //load webservice ngan hang
        public static List<BANK_WEBSERVICE> getAllBank()
        {
           
            try
            {
                var result = from bank in qldoanhnghiep.BANK_WEBSERVICEs
                             select bank;
                return result.ToList();
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static string getBankUrl(string bankID)
        {

            try
            {
                BANK_WEBSERVICE bank = qldoanhnghiep.BANK_WEBSERVICEs.Single(b => b.Bank_WS_ID == bankID);
                if(bank != null)
                    return bank.BankWebservice_Url;

                return "";
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public static void getBankAccountWebservice(ref string username, ref string password,string bankID)
        {

            try
            {
                AccountBankWebservice accountBank = qldoanhnghiep.AccountBankWebservices.Single(acc => acc.BankWS_ID == bankID);
                if (accountBank != null)
                {
                    username = accountBank.Username;
                    password = accountBank.Password;
                }

            }
            catch (Exception ex)
            {
                username = "";
                password = "";
            }
        }

        //lay so the thanh toan cua doanh nghiep biz ung voi ngan hang do
        public static string getSoTheThanhToanDNBiz(string bankID)
        {
            try
            {
                AccountBankWebservice accountBank = qldoanhnghiep.AccountBankWebservices.Single(acc => acc.BankWS_ID == bankID);
                if (accountBank != null)
                {
                    return accountBank.MaTaiKhoan;
                }
                return "";
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        //goi van chuyen cho thanh toan truc tiep tu trang web
        public static string Transport(string transCompanyId, string transTypeId, string validationCode, ContactInfo contact,ref int quantity)
        {
            string url = "";
            try
            {


                //kiem tra co ton tai transportCompanyID nay ko
                var checkTransportCompanyID = from transCompany in qldoanhnghiep.TRANSPORT_WEBSERVICEs
                                              where transCompany.TRANSPORT_WS_ID == int.Parse(transCompanyId)
                                              select transCompany;
                if (checkTransportCompanyID.Count() == 1)
                {
                    //goi WS van chuyen
                    TransportWS.FedexWebService1 transportWS = new TMDT_Nhom1A.TransportWS.FedexWebService1();

                    //lay thong tin url Webservice van chuyen dang xai
                    string transportUrl = CouponUtil.GetUrlTransportWebservice(qldoanhnghiep, transCompanyId);
                    transportWS.Url = transportUrl;

                    string userName = "";
                    string passWord = "";
                    //gọi hàm authenticate
                    var accountTransportWS = from acc in qldoanhnghiep.AccountTransportWebservices
                                             where acc.TransportWS_ID == int.Parse(transCompanyId)
                                             select acc;
                    if (accountTransportWS.Count() == 1)
                        foreach (var accountItem in accountTransportWS)
                        {
                            userName = accountItem.Username;
                            passWord = accountItem.Password;
                        }

                    //goi ham authenticate
                    string sid = transportWS.Authenticate(userName, passWord);


                    if (sid != "" && sid != null)
                    {
                        //kiem tra xem co ton tai validationCode
                        var orderB2BResult = from o in qldoanhnghiep.ORDER_B2Bs
                                             where o.OrderB2B_ID == validationCode
                                             select 0;

                        if (orderB2BResult.Count() >= 1)
                        {
                            //tinh tong so luong san pham
                            //int quantity = 0;
                            var orderB2BDetail = from orderDetail in qldoanhnghiep.ORDER_DETAILs
                                                 where orderDetail.OrderB2B_ID == validationCode
                                                 select orderDetail;
                            if (orderB2BDetail.Count() >= 1)
                            {
                                foreach (var item in orderB2BDetail)
                                {
                                    quantity += (int)item.Quantity;
                                }
                                //lay ra couponID  
                                //tao ra dia chi
                                //string customerAddress = contact.Email + "||" + contact.SoDienThoai + "||" + contact.DiaChi;
                                string customerAddress = contact.DiaChi;
                                url = transportWS.TransportGoods(sid, validationCode, quantity, DateTime.Now, customerAddress, int.Parse(transTypeId), "Q4, Nha Trang");
                            }
                            else
                            {
                                return "";
                            }
                                                     
                        }
                        else
                        {
                            return ErrorCode.ConfirmOrderNotExistValidationCodeERR;
                        }

                    }
                }

                return url;

            }
            catch
            {
                return ErrorCode.ConfirmOrderERR;
            }
        }

        public static bool UpdateStatusOrderAfterCheckout(string orderB2BID,string bankID,int transportCompanyID,string transportType,string url)
        {
            try
            {
                ORDER_B2B orderB2B = qldoanhnghiep.ORDER_B2Bs.Single(o => o.OrderB2B_ID == orderB2BID);

                if (orderB2B != null)
                {
                    orderB2B.status = 1;
                    orderB2B.PaymentStatus = 1;
                    orderB2B.TransportStatus = 1;
                    orderB2B.Transport_WS_ID = transportCompanyID;
                    orderB2B.Bank_WS_ID = bankID;
                    orderB2B.OrderTransportDate = DateTime.Now;
                    orderB2B.TransportType = transportType;
                    orderB2B.LinkTranport = url;

                    qldoanhnghiep.SubmitChanges();
                    return true;
                }
                return false;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
    }
}
